package com.starblink.android.basic.widget.edittext;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.viewpager.widget.ViewPager;

import com.starblink.android.basic.R;
import com.starblink.basic.autosize.utils.AutoSizeUtils;
import com.starblink.basic.util.AnimationBlinkUtils;

import org.jetbrains.annotations.NotNull;

/**
 * @author huaweixia
 * @description 自带清除功能的密码输入框
 * @date 2020/12/28 9:54
 */
public class ClearEditText extends RelativeLayout {
    private EditText myEdie;
    private ImageView ivEditClean;
    private ImageView ivEditEye;
    private boolean isChecked = true;
    private Context mContext;
    private TypedArray mTypedArray;
    private boolean showClean = true;//清空图标是否显示，true:显示
    private boolean showEye = false;//密码可见图标是否显示，true:显示
    private int drawableLeft = -1;//是否显示输入框左侧图片
    private int drawableEyeOpen = R.drawable.psd_visibility;//可以看见密码小眼睛样式
    private int drawableEyeClose = R.drawable.psd_visibility_off;//不可见密码小眼睛样式
    private int drawableClean = R.drawable.text_field_clear;//清除按钮图片
    private int cleanPadding = 0;//清除按钮padding边距
    private String hintStr;
    private String textStr;
    private int mTextColorHint = Color.BLACK;
    private int mTextColor = Color.BLACK;
    private int mTextSize = -1;
    private int mMaxLength = 2000;
    private int mMaxLines = 1;
    private int mInputType = 0;//输入类型，就做了不限制、数字、文本密码三种
    private boolean isInput = false;//输入1个字符后更改状态为true,保证小眼睛移动一次
    private boolean isHideClean = false;//输入字符后，清除了需要小眼睛归为，清除按钮隐藏
    private int ivWidth = 45;//关闭按钮的宽度

    public ClearEditText(Context context) {
        super(context);
        mContext = context;
        initView();
    }

    public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        mTypedArray = mContext.obtainStyledAttributes(attrs, R.styleable.myEditText);
        initView();
    }

    public ClearEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mTypedArray = mContext.obtainStyledAttributes(attrs, R.styleable.myEditText);
        showClean = mTypedArray.getBoolean(R.styleable.myEditText_showClean, showClean);
        drawableClean = mTypedArray.getResourceId(R.styleable.myEditText_drawableClean, drawableClean);
        cleanPadding = mTypedArray.getDimensionPixelSize(R.styleable.myEditText_cleanPadding, cleanPadding);

        showEye = mTypedArray.getBoolean(R.styleable.myEditText_showEye, showEye);
        drawableLeft = mTypedArray.getResourceId(R.styleable.myEditText_drawableLeft, -1);
        drawableEyeClose = mTypedArray.getResourceId(R.styleable.myEditText_drawableEyeClose, drawableEyeClose);
        drawableEyeOpen = mTypedArray.getResourceId(R.styleable.myEditText_drawableEyeOpen, drawableEyeOpen);

        hintStr = mTypedArray.getString(R.styleable.myEditText_hint);
        textStr = mTypedArray.getString(R.styleable.myEditText_text);
        mTextColorHint = mTypedArray.getColor(R.styleable.myEditText_textColorHint, mTextColorHint);
        mTextColor = mTypedArray.getColor(R.styleable.myEditText_textColor, mTextColor);
        mTextSize = mTypedArray.getDimensionPixelSize(R.styleable.myEditText_textSize, mTextSize);
        mMaxLength = mTypedArray.getInteger(R.styleable.myEditText_maxLength, mMaxLength);
        mMaxLines = mTypedArray.getInteger(R.styleable.myEditText_maxLines, mMaxLines);
        mInputType = mTypedArray.getInteger(R.styleable.myEditText_inputType, mInputType);

        mTypedArray.recycle();
        initView();
    }

    // 初始化视图
    private void initView() {
        View view = View.inflate(getContext(), R.layout.clear_layout_view, null);
        myEdie = (EditText) view.findViewById(R.id.view_edit_show);
        ivEditClean = (ImageView) view.findViewById(R.id.iv_edit_clean);
        ivEditEye = (ImageView) view.findViewById(R.id.iv_edit_eye);

        //用shape曲线更圆滑
        //圆角边框
        //https://blog.csdn.net/weixin_30270561/article/details/98935445
//        float rv = AutoSizeUtils.dp2px(mContext, 7.5f);
//        float rvIn = AutoSizeUtils.dp2px(mContext, 8f);
//        float[] externalRound = {rv, rv, rv, rv, rv, rv, rv, rv};
//        RectF distanceRectF = new RectF(rvIn, rvIn, rvIn, rvIn);
//        float[] insideRound = {rvIn, rvIn, rvIn, rvIn, rvIn, rvIn, rvIn, rvIn};
//        ShapeDrawable shapeDrawable = new ShapeDrawable(new RoundRectShape(externalRound, null, insideRound));
//        ShapeDrawable shapeDrawable = new ShapeDrawable();
//        Paint paint = shapeDrawable.getPaint();
//        paint.setColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray300));
//        paint.setStyle(Paint.Style.STROKE);
//        paint.setStrokeWidth(1);
//        view.setBackground(shapeDrawable);


        myEdie.setHint(hintStr);
        myEdie.setHintTextColor(mTextColorHint);
        myEdie.setText(textStr);
        myEdie.setTextColor(mTextColor);
        myEdie.setMaxLines(mMaxLines);
        myEdie.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mMaxLength)});
        if (mTextSize != -1) {
            myEdie.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        } else {
            myEdie.setTextSize(15);
        }
        if (mInputType == 1) {
            myEdie.setInputType(InputType.TYPE_CLASS_NUMBER);
        } else if (mInputType == 2) {
            myEdie.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
        } else {
            myEdie.setInputType(InputType.TYPE_NUMBER_VARIATION_NORMAL | InputType.TYPE_CLASS_TEXT);
        }
        if (showEye) {
            myEdie.setTransformationMethod(new AsteriskPasswordTransformationMethod());
        }
//        if (showClean && showEye) {
//            int left = myEdie.getPaddingLeft();
//            int top = myEdie.getPaddingTop();
//            int right = myEdie.getPaddingRight();
//            int bottom = myEdie.getPaddingBottom();
////            myEdie.setPadding(left, top, AutoSizeUtils.dp2px(mContext, 16), bottom);
//            myEdie.setPadding(left, top, right, bottom);
//        } else if (!showClean && !showEye) {
//            int left = myEdie.getPaddingLeft();
//            int top = myEdie.getPaddingTop();
//            int right = myEdie.getPaddingRight();
//            int bottom = myEdie.getPaddingBottom();
//            myEdie.setPadding(left, top, right, bottom);
//        } else {
//            int left = myEdie.getPaddingLeft();
//            int top = myEdie.getPaddingTop();
//            int bottom = myEdie.getPaddingBottom();
//            myEdie.setPadding(left, top, AutoSizeUtils.dp2px(mContext, 16), bottom);
//        }

        myEdie.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    isHideClean = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0 && !isInput) {//输入字符大于0且只有一个字符时候显示清除按钮动画，小眼睛移动出位置给清除按钮使用
                    showEditClean();

                    if(showEye){
                        setEditEye(true);
                    }else{
                        moveEditEye();
                    }
                    isInput = true;
                } else if (s.length() == 0) {//无字符小眼睛归位
                    if(showEye){
                        UndoEditEye();
                    }
                }
                if (s.length() == 0 & !isHideClean) {
                    hideEditClean();
                    isHideClean = true;
                    isInput = false;
                }
                if (onEditInputListener != null) {
                    onEditInputListener.input(getText());
                }
            }
        });
        myEdie.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (onFocusChangeListener != null) {
                    onFocusChangeListener.onFocusChange(v, hasFocus);
                }
            }
        });

        setEditClean(showClean);
        ivEditClean.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                myEdie.setText("");
            }
        });
        ivEditClean.setImageResource(drawableClean);
        ivEditClean.setPadding(cleanPadding, cleanPadding, cleanPadding, cleanPadding);

        setEditEye(showEye);
        ivEditEye.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isChecked) {
                    // 输入一个对用户可见的密码
                    myEdie.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    myEdie.setSelection(getText().length());
                    ivEditEye.setImageResource(drawableEyeOpen);
                    isChecked = false;
                } else {
                    // 输入一个对用户不可见的密码
                    myEdie.setTransformationMethod(new AsteriskPasswordTransformationMethod());
                    myEdie.setSelection(getText().length());
                    ivEditEye.setImageResource(drawableEyeClose);
                    isChecked = true;
                }
            }
        });
//        if (drawableLeft != -1) {
//            ivLeftIcon.setVisibility(View.VISIBLE);
//            ivLeftIcon.setImageResource(drawableLeft);
//        } else {
//            ivLeftIcon.setVisibility(View.GONE);
//        }
        view.setLayoutParams(new LayoutParams(ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT));
        addView(view);
    }

    //密码不可见时候，使用*替换密码
    public class AsteriskPasswordTransformationMethod extends PasswordTransformationMethod {
        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return new PasswordCharSequence(source);
        }

        private class PasswordCharSequence implements CharSequence {

            private CharSequence mSource;

            public PasswordCharSequence(CharSequence source) {
                mSource = source; // Store char sequence
            }

            @Override
            public char charAt(int index) {
                return '*'; // This is the important part
            }

            @Override
            public int length() {
                return mSource.length(); // Return default
            }

            @Override
            public CharSequence subSequence(int start, int end) {
                return mSource.subSequence(start, end); // Return default
            }
        }

    }

    public String getText() {
        return myEdie.getText().toString().trim();
    }

    public void setText(String text) {
        myEdie.setText(text);
    }

    public void setHint(@NotNull String text) {
        myEdie.setHint(text);
    }

    public EditText getEditText() {
       return myEdie;
    }

    public void clearEditFocus() {
        myEdie.clearFocus();
    }

    //代码设置是否显示清除按钮
    public void setEditClean(boolean isCanClose) {
        showClean = isCanClose;
    }

    //代码设置是否显示小眼睛
    public void setEditEye(boolean isCanSee) {
        showEye = isCanSee;
        if (showEye == true) {
            ivEditEye.setVisibility(View.VISIBLE);
        } else {
            ivEditEye.setVisibility(View.GONE);
        }
    }

    private void showEditClean() {
        if (showClean == true) {
            AnimationBlinkUtils.showAndHiddenCenterAnimation(ivEditClean, AnimationBlinkUtils.AnimationState.STATE_SHOW, 500);
        }
    }

    private void hideEditClean() {
        if (showClean == true) {
            AnimationBlinkUtils.showAndHiddenCenterAnimation(ivEditClean, AnimationBlinkUtils.AnimationState.STATE_HIDDEN, 500);
        }
    }

    private void moveEditEye() {
        if (showEye) {
            ObjectAnimator.ofFloat(ivEditEye, "translationX", -AutoSizeUtils.dp2px(mContext, ivWidth)).setDuration(500).start();
        }
    }

    private void UndoEditEye() {
        if (showEye) {
            ObjectAnimator.ofFloat(ivEditEye, "translationX", 0).setDuration(500).start();
        }
    }

    public OnEditInputListener onEditInputListener;

    public void setOnEditInputListener(OnEditInputListener listener) {
        onEditInputListener = listener;
    }

    public OnFocusChangeListener onFocusChangeListener;

    public void setOnEditFocusChangeListener(OnFocusChangeListener listener) {
        onFocusChangeListener = listener;
    }

    //输入监听
    public interface OnEditInputListener {
        void input(String content);
    }
}